package utils;

import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.viapiutils.model.v20200401.GetOssStsTokenRequest;
import com.aliyuncs.viapiutils.model.v20200401.GetOssStsTokenResponse;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * 文件上传到oss并获取地址
 * 配合身份识别使用
 */
public class MyFileUtils {
    DefaultAcsClient client;
    String endpoint = "viapiutils.cn-shanghai.aliyuncs.com";
    String accessKeyId;
    Pattern fileNameRegex = Pattern.compile("\\w+.(jpg|gif|png|jpeg|bmp|mov|mp4|avi)");
    static Map<String, MyFileUtils> map = new HashMap();

    public static synchronized MyFileUtils getInstance(String accessKeyId, String accessKeySecret) throws ClientException {
        String mapKey = accessKeyId + accessKeySecret;
        MyFileUtils myFileUtils = (MyFileUtils) map.get(mapKey);
        if (myFileUtils == null) {
            myFileUtils = new MyFileUtils(accessKeyId, accessKeySecret);
            map.put(mapKey, myFileUtils);
        }
        return myFileUtils;
    }

    private MyFileUtils(String accessKeyId, String accessKeySecret) throws ClientException {
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("", "cn-shanghai", "viapiutils", this.endpoint);
        this.client = new DefaultAcsClient(profile);
        this.accessKeyId = accessKeyId;
    }

    public String upload(InputStream inputStream) throws ClientException, IOException {
        String var18;
        try {
            GetOssStsTokenRequest getOssStsTokenRequest = new GetOssStsTokenRequest();
            GetOssStsTokenResponse getOssStsTokenResponse = (GetOssStsTokenResponse)this.client.getAcsResponse(getOssStsTokenRequest);
            String akKey = getOssStsTokenResponse.getData().getAccessKeyId();
            String akSec = getOssStsTokenResponse.getData().getAccessKeySecret();
            String token = getOssStsTokenResponse.getData().getSecurityToken();
            OSSClient ossClient = new OSSClient("http://oss-cn-shanghai.aliyuncs.com", akKey, akSec, token);
            String key = this.accessKeyId + "/" + UUID.randomUUID().toString();
            ossClient.putObject("viapi-customer-temp", key, inputStream);
            var18 = "http://viapi-customer-temp.oss-cn-shanghai.aliyuncs.com/" + key;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return var18;
    }
}
